const User = require('../models/User');
const UserCheckin = require('../models/UserCheckin');
const { sendResponse, sendListResponse } = require('../utils/response');
const moment = require('moment');
const { formatTime, formatObject } = require('../utils/common');

// 用户手动签到
exports.userCheckin = async (req, res) => {
  const userId = req.body.userId;

  try {
    // 用于比较的今天日期(仅年月日)
    const todayStr = formatTime(new Date(), 'YYYY-MM-DD');
    let checkinInfo = await UserCheckin.findOne({ where: { user_id: userId } });
    let streakDays = 1;
    let checkinMessage = '';

    if (checkinInfo) {
      // 获取上次签到日期的字符串格式用于比较
      const lastCheckinDateStr = formatTime(checkinInfo.checkin_date, 'YYYY-MM-DD');

      if (lastCheckinDateStr === todayStr) {
        // 今天已经签到过了
        sendResponse(res, 200, "今日已签到", {
          streakDays: checkinInfo.streak_days,
          lastCheckin: formatTime(checkinInfo.checkin_date, 'YYYY-MM-DD'),
          lastCheckinTime: formatTime(checkinInfo.checkin_time, 'YYYY-MM-DD HH:mm:ss'),
          maxStreak: checkinInfo.max_streak
        });
        return;
      }

      if (moment(todayStr).diff(moment(lastCheckinDateStr), 'days') === 1) {
        // 连续签到（昨天签到过）
        streakDays = checkinInfo.streak_days + 1;
        checkinMessage = `连续签到${streakDays}天`;
      } else {
        // 中断了连续签到
        streakDays = 1;
        checkinMessage = '签到成功';
      }

      // 更新最大连续签到天数
      const maxStreak = Math.max(checkinInfo.max_streak, streakDays);

      // 更新签到记录 - 使用原生Date对象
      await checkinInfo.update({
        checkin_date: new Date(),
        checkin_time: new Date(),
        streak_days: streakDays,
        max_streak: maxStreak,
        checkin_history: [...(checkinInfo.checkin_history || []), {
          checkin_date: formatTime(new Date(), 'YYYY-MM-DD'),
          checkin_time: formatTime(new Date(), 'YYYY-MM-DD HH:mm:ss')
        }]
      });
    } else {
      // 首次签到
      checkinMessage = '首次签到';
      checkinInfo = await UserCheckin.create({
        user_id: userId,
        checkin_date: new Date(),
        checkin_time: new Date(),
        streak_days: 1,
        max_streak: 1,
        checkin_history: [{
          checkin_date: formatTime(new Date(), 'YYYY-MM-DD'),
          checkin_time: formatTime(new Date(), 'YYYY-MM-DD HH:mm:ss')
        }]
      });
      streakDays = 1;
    }

    // 返回时格式化日期
    sendResponse(res, 200, checkinMessage, {
      streakDays: streakDays,
      lastCheckin: formatTime(checkinInfo.checkin_date, 'YYYY-MM-DD'),
      lastCheckinTime: formatTime(checkinInfo.checkin_time, 'YYYY-MM-DD HH:mm:ss'),
      maxStreak: checkinInfo.max_streak
    });
  } catch (error) {
    console.error("签到失败:", error);
    sendResponse(res, 500, "签到失败");
  }
};

// 判断用户今天是否签到
exports.isCheckin = async (req, res) => {
  const userId = req.query.userId;
  const todayStr = formatTime(new Date(), 'YYYY-MM-DD');

  try {
    const checkinInfo = await UserCheckin.findOne({ where: { user_id: userId } });

    if (!checkinInfo) {
      // 用户从未签到过
      sendResponse(res, 200, "未签到");
      return;
    }

    // 获取最后签到日期（只保留年月日部分）
    const lastCheckinDateStr = formatTime(checkinInfo.checkin_date, 'YYYY-MM-DD');

    // 判断最后签到日期是否为今天
    if (lastCheckinDateStr === todayStr) {
      sendResponse(res, 200, "已签到", {
        streakDays: checkinInfo.streak_days,
        lastCheckin: formatTime(checkinInfo.checkin_date, 'YYYY-MM-DD'),
        lastCheckinTime: formatTime(checkinInfo.checkin_time, 'YYYY-MM-DD HH:mm:ss'),
        maxStreak: checkinInfo.max_streak
      });
    } else {
      sendResponse(res, 200, "未签到");
    }
  } catch (error) {
    console.error("检查签到失败:", error);
    sendResponse(res, 500, "检查签到失败");
  }
};

// 获取用户签到历史
exports.getCheckinHistory = async (req, res) => {
  const userId = req.query.userId;
  const page = parseInt(req.query.page) || 1;
  const pageSize = parseInt(req.query.pageSize) || 20;

  try {
    const checkinInfo = await UserCheckin.findOne({ where: { user_id: userId } });

    if (!checkinInfo || !checkinInfo.checkin_history || checkinInfo.checkin_history.length === 0) {
      sendListResponse(res, 200, "获取成功", [], 0);
      return;
    }

    const checkinHistory = checkinInfo.checkin_history;
    const total = checkinHistory.length;

    // 计算分页
    const startIndex = (page - 1) * pageSize;
    const endIndex = Math.min(startIndex + pageSize, total);
    const paginatedHistory = checkinHistory.slice(startIndex, endIndex);
    const list = paginatedHistory.map(item => formatObject(item));

    sendListResponse(res, 200, "获取成功", list, total);
  } catch (error) {
    console.error("获取签到历史失败:", error);
    sendResponse(res, 500, "获取签到历史失败");
  }
}; 
